package com.direct.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.direct.common.SystemConstant;
import com.direct.dao.BaseDao;
import com.direct.domian.Entity;


public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 *添加
	 */
	public void add(T t) {
		getSession().save(t);
	}

	/**
	 * 修改
	 */
	public void update(T t) {
		getSession().update(t);
	}
	
	/**
	 * 删除
	 */
	public void delete(T t) {
		Entity e = (Entity) getSession().load(t.getClass(), ((Entity) t).getId());
		e.setValid(SystemConstant.INVALID);
		update((T)e);
	}

	/**
	 * 根据id查询一条数据
	 */
	public T queryById(Class c,Serializable id) {
		return (T) getSession().get(c, id);
	}

	
	public T querySingle(String hql, Object[] params) {
			List<T> ls = (List<T>) getQuery(hql, params).list();
				if(ls!=null&&ls.size()>0){
					return ls.get(0);
				}
		return null;
	}

	/**
	 * 查询总条数
	 */
	public long queryCount(String hql, Object[] params) {
		StringBuilder hqlBuilder = new StringBuilder();
		hqlBuilder.append("select count(*) from ");
		hqlBuilder.append(hql);
		//hqlBuilder.append(" ) ");
		return (Long) getQuery(hqlBuilder.toString(), params).iterate().next();
	}

	/**
	 * 不分页查询所有
	 */
	public List<T> queryList(String hql, Object[] params) {
		return getQuery(hql, params).list();
	}
	
	/**
	 * 分页查询所有
	 */
	public List<T> queryList(String hql, Object[] params, int pn, int pr) {
		Query query = getQuery(hql, params);
		
		query.setFirstResult(((pn-1)*pr) + 1);
		query.setMaxResults(pr);
		
		return query.list();
	}
	
	/**
	 * 公共代码
	 * @param hql
	 * @param params
	 * @return
	 */
	private Query getQuery(String hql,Object[] params) {
		Session session = getSession();
		Query query = session.createQuery(hql);
		if(params != null && params.length > 0) {
			for (int i = 0; i < params.length; i++) {
				query.setParameter(i, params[i]);
			}
		}
		return query;
	}
}
